package com.example.deadqueue.controller;


import com.example.deadqueue.config.DelayedQueueConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * @author Tonysong
 * @version 1.0
 */
@Slf4j
@RestController
@RequestMapping("/ttl")
public class SendMsgController {
    @Autowired
    RabbitTemplate rabbitTemplate;
    //发送我们基础死信消息
    @GetMapping("/sendMsg/{message}")
    public void sendMsg(@PathVariable String message){
        log.info("当前时间:{}, 发送一条消息给两个TTL队列: {}", new Date().toString(), message);
        rabbitTemplate.convertAndSend("X", "XA", "消息来自ttl为10s的队列" + message);
        rabbitTemplate.convertAndSend("X", "XB", "消息来自ttl为40s的队列" + message);
    }

    //发送我们优化后的延迟队列的消息
    @GetMapping("/sendExpirationMsg/{message}/{ttlTime}")
    public void sendMsg(@PathVariable String message, @PathVariable String ttlTime){
        log.info("当前时间:{}, 发送一条时长为{}毫秒的消息给TTL队列QC: {}", new Date().toString(), ttlTime, message);
        //使用springboot为我们提供的rabbitTemplate来发送延迟消息
        rabbitTemplate.convertAndSend("X", "XC", message, msg -> {
            //设置过期时间
            msg.getMessageProperties().setExpiration(ttlTime);
            return msg;
        });
    }

    //发送我们使用插件的延迟队列消息
    @GetMapping("/sendDelayedMsg/{message}/{delayedTime}")
    public void sendMsg(@PathVariable String message, @PathVariable Integer delayedTime){
        log.info("当前时间:{}, 发送一条时长为{}毫秒的消息给延迟队列delayed.queue: {}", new Date().toString(), delayedTime, message);
        rabbitTemplate.convertAndSend(DelayedQueueConfig.DELAYED_EXCHANGE_NAME, DelayedQueueConfig.DELAYED_ROUTING_KEY, message, msg -> {
            //设置延迟消息
            msg.getMessageProperties().setDelay(delayedTime);
            return msg;
        });
    }

}
